<template>
	<view class="container">
		<custom-status-bar></custom-status-bar>
		<!-- 搜索栏 -->
		<view class="header">
			<view class="back-icon" @click="goBack">
				<uni-icons type="left" size="20" color="#666"></uni-icons>
				<text>返回</text>
			</view>
			<uni-search-bar class="search-bar" v-model="keyword" cancelButton="none" @confirm="search"
				@input="handleSearch"></uni-search-bar>
		</view>
		<uv-vtabs :chain="false" :list="list" @change="change">
			<uv-vtabs-item>
				<view class="product-list">
					<view class="product-item" v-for="(item2, index2) in list2" :key="index2" @click="gotoDetail(item2.pid)">
						<image :src="item2.smallImg" class="product-image" />
						<view class="product-info">
							<view class="product-name">{{ item2.name }}</view>
							<view class="product-english">{{ item2.enname }}</view>
							<view class="price-tag">¥{{ item2.price }}</view>
							<view v-if="item2.isHot" class="hot-tag">热卖</view>
						</view>
					</view>
				</view>
			</uv-vtabs-item>
		</uv-vtabs>
	</view>
</template>
<script setup>
	import CustomStatusBar from '../../components/common/CustomStatusBar.vue';
	// import nuanf-class-select from "../../components/nuanf-class-select/nuanf-class-select.vue"
	import {
		ref,
		onMounted,
		computed
	} from 'vue';
	import {
		getProductType,
		getProductsByType
	} from "@/api/index.js"
	
	const keyword=ref('')

    const categories=ref([])
	const list = ref([])
	const tabIndex = ref(0)
	const list2 = computed(() => {
		  const currentTab = list.value[tabIndex.value];
		  console.log("currentTab",currentTab)
		  return currentTab?.children ? currentTab.children : [];
	})
	const uniqueByKey = (arr, key) => {
		const map = new Map();
		return arr.filter(item => !map.has(item[key]) && map.set(item[key], true));
	}

	onMounted(async () => {
		uni.showLoading({
			title: '加载中'
		})
		//加载分类
		const type = await getProductType()
		console.log("type:", type)
		categories.value = uniqueByKey(type.result, 'type')
		console.log(" categories:", categories.value);
		
		// categories
		// {
		//     "id": 1,
		//     "type": "latte",
		//     "typeDesc": "拿铁",
		//     "createdAt": "2025-06-20T05:09:03.000Z",
		//     "updatedAt": "2025-06-20T05:09:03.000Z"
		// }
		
		// categories.value = categories.value.map(item => item.typeDesc)
		// console.log("onMounted categories:", categories.value);
		
		// [
		//     "拿铁",
		//     "咖啡",
		//     "瑞纳冰",
		//     "水果茶"
		// ]
		
		// 热卖
		const hotProducts = await getProductsByType('isHot', 1)
		console.log("hotProducts:", hotProducts.result);
		
		// hotProducts {id: 7, pid: 'latte004', type: 'coffee', name: '焦糖拿铁', price: '28.00', …}
		
		
		const products = await Promise.all(categories.value.map(async (category) => {
			try {
				const res = await getProductsByType('type', category.type)
				 console.log("res",res);
				return {
					name: category.typeDesc,
					children: res.result
				} // 返回类型和对应数据
			} catch (error) {
				console.error(`Failed to fetch products for type ${type}:`, error)
			}
		}))
		list.value = [{
			name: '热卖',
			children: hotProducts.result
		}, ...products]
		console.log("list:", list.value)
		console.log("list2:", list2.value)
		uni.hideLoading()
	})
	const handleSearch = (event) => {
		console.log('搜索内容:', event.detail.value);
		// 实际开发中调用搜索接口
	};
	const change = (index) => {
	console.log("change:",index)
	  tabIndex.value = index
	console.log("list:", list.value)
	console.log("list2:", list2.value)
	};
	const navigateTo = (path) => {
		uni.navigateTo({
			url: path
		});
	};
	
	const gotoDetail = (pid)=>{
		uni.navigateTo({
			url:`/pages/detail/detail?pid=${pid}`
		})
	}
	
	const search = () => {
	  // 跳转到搜索页
	  uni.navigateTo({
	    url: `/pages/search/search?query=${keyword.value}`,
	
	  })
	}
	
	
	const goBack = ()=>{
		const pages = getCurrentPages();
		if (pages.length > 1) uni.navigateBack();
			else  uni.switchTab({ url: '/pages/index/index' });
	}
	
</script>
<style scoped>
	.container {
		padding: 0 20rpx;
	}

	.header {
		display: flex;
		align-items: center;
		height: 100rpx;
		border-bottom: 1rpx solid #eee;

	}

	.back-icon {
		display: flex;
		align-items: center;
		font-size: 28rpx;
		margin-right: 40rpx;
	}

	.search-bar {
	        display: flex;
			align-items: center;
			background: #F5F5F5;
			border-radius: 40rpx;
			flex: 1;
			padding: 0 20rpx;
			

	}

	.search-bar text {
		margin-left: 10rpx;
		font-size: 20rpx;
		color: #666;
	}

	.category-nav {
		display: flex;
		height: calc(100vh - 400rpx);
	}

	.nav-list {
		width: 120rpx;
		padding: 20rpx;
		border-right: 1rpx solid #eee;
	}

	.nav-list text {
		display: block;
		padding: 20rpx 0;
		text-align: center;
		font-size: 28rpx;
	}

	.nav-list .active {
		color: #007AFF;
		font-weight: bold;
		border-left: 4rpx solid #007AFF;
	}

	.product-list {
		/* width: calc(100% - 120rpx); */
		padding-left: 20rpx;
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 20rpx;
	}

	.product-item {
		position: relative;
		background: white;
		border-radius: 12rpx;
		overflow: hidden;
	}

	.product-image {
		width: 100%;
		height: 200rpx;
		border-radius: 12rpx;
	}

	.product-info {
		padding: 20rpx;
		position: relative;
	}

	.product-name {
		font-size: 28rpx;
		margin-bottom: 10rpx;
		color: #333;
	}

	.product-english {
		font-size: 24rpx;
		color: #999;
		margin-bottom: 20rpx;
	}

	.price-tag {
		position: absolute;
		right: 20rpx;
		bottom: 20rpx;
		color: red;
		font-weight: bold;
		font-size: 28rpx;
	}

	.hot-tag {
		position: absolute;
		top: 20rpx;
		right: 20rpx;
		background: red;
		color: white;
		padding: 4rpx 8rpx;
		border-radius: 4rpx;
		font-size: 20rpx;
	}
</style>